﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Data.OleDb;
using System.Data;
using System.Xml.Linq;
using System.Xml;
using System.Net;
using System.IO;
using System.Collections;
using System.Windows.Threading;

namespace ExpenseIt
{
    public partial class onlineModePage : Page
    {
        List<XElement> Userlist = new List<XElement>();
        public onlineModePage()
        {
            InitializeComponent();
            StringBuilder sb = new StringBuilder();
            byte[] buf = new byte[8192];
            HttpWebRequest request = (HttpWebRequest)
            /*FOR ONLINE SERVICE*/
            //WebRequest.Create("http://www.digiply.com:8020/MyAPIWebService.svc/getUser");
            /*FOR LOCAL*/
            WebRequest.Create("http://localhost:45207/MyAPIWebService.svc/getUser");
            try
            {
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                Stream resStream = response.GetResponseStream();
                string tempString = null;
                int count = 0;
                do
                {
                    count = resStream.Read(buf, 0, buf.Length);
                    if (count != 0)
                    {
                        tempString = Encoding.ASCII.GetString(buf, 0, count);
                        sb.Append(tempString);
                    }
                }
                while (count > 0); // any more data to read?
                XElement TrackList = XElement.Parse(sb.ToString());
                XmlDocument doc = new XmlDocument();
                LibraryView.DataContext = TrackList;
            }
            catch 
            {
                //offlineModePage OFMPage = new offlineModePage();
                //this.NavigationService.Navigate(OFMPage);
            }
        }

        void OnChecked(object sender, RoutedEventArgs e)
        {
            XElement element = (XElement)LibraryView.SelectedItems[0];
            Userlist.Add(element);
        }
        void OnUnchecked(object sender, RoutedEventArgs e)
        {
            XElement element = (XElement)LibraryView.SelectedItems[0];
            Userlist.Remove(element);
        }
        private void button1_Click_1(object sender, RoutedEventArgs e)
        {
            var pathOfExe = System.AppDomain.CurrentDomain.BaseDirectory;
            var relativeToExe=pathOfExe+"test.mdb";
            var con = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source = " + relativeToExe);
            var cmd = new OleDbCommand();
            cmd.Connection = con;
            con.Open(); // open the connection
            /*
            string queryToDropTable = "DROP TABLE Clients";
            cmd = new OleDbCommand(queryToDropTable, con);
            
                cmd.ExecuteNonQuery();
            
            
            string queryToMakeTable = "CREATE TABLE Clients";
            cmd = new OleDbCommand(queryToMakeTable, con);
            cmd.ExecuteNonQuery();
            */
            foreach (XElement Object in Userlist)
            {
                foreach (var el in Object.Descendants()) //making fields
                {
                    //string query = "CREATE TABLE Clients (['" + el.Name.ToString() + "'] TEXT(80))";
                    if ((el.Name.ToString() != ("EntityKey")) && (el.Name.ToString() != ("EntitySetName")) && (el.Name.ToString() != ("EntityContainerName")) && (el.Name.ToString() != ("EntityKeyValues")) && (el.Name.ToString() != ("EntityKeyMember")) && (el.Name.ToString() != ("Key")) && (el.Name.ToString() != ("Value")))
                    {
                        string query = "ALTER TABLE Clients ADD '" + el.Name.ToString() + "' MEMO";

                        cmd = new OleDbCommand(query, con);
                        try
                        {
                            cmd.ExecuteNonQuery();
                        }
                        catch
                        {
                        }
                    }
                }
                string query2 = "ALTER TABLE Clients ADD 'Last_Updated' MEMO";
                cmd = new OleDbCommand(query2, con);
                try
                {
                    cmd.ExecuteNonQuery();
                }
                catch
                {
                }

                ArrayList listOfFielsName = new ArrayList();
                ArrayList listOfFielsValue = new ArrayList();
                foreach (var el in Object.Descendants())
                {
                    if ((el.Name.ToString() != ("EntityKey")) && (el.Name.ToString() != ("EntitySetName")) && (el.Name.ToString() != ("EntityContainerName")) && (el.Name.ToString() != ("EntityKeyValues")) && (el.Name.ToString() != ("EntityKeyMember")) && (el.Name.ToString() != ("Key")) && (el.Name.ToString() != ("Value")))
                    {
                        listOfFielsName.Add(el.Name.ToString());


                        if (el.Name == ("ClientId"))
                        {
                            Console.WriteLine(el.Value);
                            string query3 = "DELETE Clients.['ClientId'] FROM Clients WHERE (((Clients.['ClientId'])='" + el.Value + "'))";
                            cmd = new OleDbCommand(query3, con);
                            try
                            {
                                cmd.ExecuteNonQuery();
                            }
                            catch
                            {
                            }
                         }
                        string temp = el.Value;
                        temp = temp.Replace("'", "\"");
                        listOfFielsValue.Add(temp);
                    }
                }

                DateTime now = DateTime.Now;
                listOfFielsName.Add("Last_Updated");
                listOfFielsValue.Add(now);

                try
                {
                string s1 = "INSERT INTO [Clients] (['" + listOfFielsName[0] + "'],['" + listOfFielsName[1] + "'],['" + listOfFielsName[2] + "'],['" + listOfFielsName[3] + "'],['" + listOfFielsName[4] + "'],['" + listOfFielsName[5] + "'],['" + listOfFielsName[6] + "'],['" + listOfFielsName[7] + "'],['" + listOfFielsName[8] + "'],['" + listOfFielsName[9] + "'],['" + listOfFielsName[10] + "'],['" + listOfFielsName[11] + "'],['" + listOfFielsName[12] + "'],['" + listOfFielsName[13] + "'],['" + listOfFielsName[14] + "'],['" + listOfFielsName[15] + "'],['" + listOfFielsName[16] + "'],['" + listOfFielsName[17] + "'],['" + listOfFielsName[18] + "'],['" + listOfFielsName[19] + "'],['" + listOfFielsName[20] + "'],['" + listOfFielsName[21] + "'],['" + listOfFielsName[22] + "'],['" + listOfFielsName[23] + "'],['" + listOfFielsName[24] + "'],['" + listOfFielsName[25] + "'],['" + listOfFielsName[26] + "'],['" + listOfFielsName[27] + "'],['" + listOfFielsName[28] + "'],['" + listOfFielsName[29] + "'],['" + listOfFielsName[30] + "'],['" + listOfFielsName[31] + "'],['" + listOfFielsName[32] + "'],['" + listOfFielsName[33] + "'],['" + listOfFielsName[34] + "'],['" + listOfFielsName[35] + "'],['" + listOfFielsName[36] + "'],['" + listOfFielsName[37] + "'],['" + listOfFielsName[38] + "'],['" + listOfFielsName[39] + "'],['" + listOfFielsName[40] + "'],['" + listOfFielsName[41] + "'],['" + listOfFielsName[42] + "'],['" + listOfFielsName[43] + "'],['" + listOfFielsName[44] + "'],['" + listOfFielsName[45] + "'],['" + listOfFielsName[46] + "'],['" + listOfFielsName[47] + "'],['" + listOfFielsName[48] + "'],['" + listOfFielsName[49] + "'],['" + listOfFielsName[50] + "'],['" + listOfFielsName[51] + "'])VALUES ('" + listOfFielsValue[0] + "','" + listOfFielsValue[1] + "','" + listOfFielsValue[2] + "','" + listOfFielsValue[3] + "','" + listOfFielsValue[4] + "','" + listOfFielsValue[5] + "','" + listOfFielsValue[6] + "','" + listOfFielsValue[7] + "','" + listOfFielsValue[8] + "','" + listOfFielsValue[9] + "','" + listOfFielsValue[10] + "','" + listOfFielsValue[11] + "','" + listOfFielsValue[12] + "','" + listOfFielsValue[13] + "','" + listOfFielsValue[14] + "','" + listOfFielsValue[15] + "','" + listOfFielsValue[16] + "','" + listOfFielsValue[17] + "','" + listOfFielsValue[18] + "','" + listOfFielsValue[19] + "','" + listOfFielsValue[20] + "','" + listOfFielsValue[21] + "','" + listOfFielsValue[22] + "','" + listOfFielsValue[23] + "','" + listOfFielsValue[24] + "','" + listOfFielsValue[25] + "','" + listOfFielsValue[26] + "','" + listOfFielsValue[27] + "','" + listOfFielsValue[28] + "','" + listOfFielsValue[29] + "','" + listOfFielsValue[30] + "','" + listOfFielsValue[31] + "','" + listOfFielsValue[32] + "','" + listOfFielsValue[33] + "','" + listOfFielsValue[34] + "','" + listOfFielsValue[35] + "','" + listOfFielsValue[36] + "','" + listOfFielsValue[37] + "','" + listOfFielsValue[38] + "','" + listOfFielsValue[39] + "','" + listOfFielsValue[40] + "','" + listOfFielsValue[41] + "','" + listOfFielsValue[42] + "','" + listOfFielsValue[43] + "','" + listOfFielsValue[44] + "','" + listOfFielsValue[45] + "','" + listOfFielsValue[46] + "','" + listOfFielsValue[47] + "','" + listOfFielsValue[48] + "','" + listOfFielsValue[49] + "','" + listOfFielsValue[50] + "','" + listOfFielsValue[51] + "')";
                cmd = new OleDbCommand(s1, con);
                cmd.ExecuteNonQuery();
                }
                catch(ArgumentOutOfRangeException ex)
                {
                    var exception = ex;
                }
               }
            con.Close();
            
            offlineModePage offlineModePage = new offlineModePage();
            this.NavigationService.Navigate(offlineModePage);
            }
        private void MenuItemHVF(object sender, RoutedEventArgs e)
        {
            caseMngHomeVisitReport CMHVRPage = new caseMngHomeVisitReport();
            this.NavigationService.Navigate(CMHVRPage);
        }
        private void MenuItemPOC(object sender, RoutedEventArgs e)
        {
            planOfCare POCPage = new planOfCare();
            this.NavigationService.Navigate(POCPage);
        }
      
        private void deleteUserIfExist(string abc)
        { 
        }



        /*Start of single click selection Code*/
        private void DataGridCell_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            DataGridCell cell = sender as DataGridCell;
            GridColumnFastEdit(cell, e);
        }

        private void DataGridCell_PreviewTextInput(object sender, TextCompositionEventArgs e)
        {
            DataGridCell cell = sender as DataGridCell;
            GridColumnFastEdit(cell, e);
        }

        private static void GridColumnFastEdit(DataGridCell cell, RoutedEventArgs e)
        {
            if (cell == null || cell.IsEditing || cell.IsReadOnly)
                return;

            DataGrid dataGrid = FindVisualParent<DataGrid>(cell);
            if (dataGrid == null)
                return;

            if (!cell.IsFocused)
            {
                cell.Focus();
            }

            if (cell.Content is CheckBox)
            {
                if (dataGrid.SelectionUnit != DataGridSelectionUnit.FullRow)
                {
                    if (!cell.IsSelected)
                        cell.IsSelected = true;
                }
                else
                {
                    DataGridRow row = FindVisualParent<DataGridRow>(cell);
                    if (row != null && !row.IsSelected)
                    {
                        row.IsSelected = true;
                    }
                }
            }
            else
            {
                ComboBox cb = cell.Content as ComboBox;
                if (cb != null)
                {
                    //DataGrid dataGrid = FindVisualParent<DataGrid>(cell);
                    dataGrid.BeginEdit(e);
                    cell.Dispatcher.Invoke(
                     //DispatcherPriority.Background,
                     new Action(delegate { }));
                    cb.IsDropDownOpen = true;
                }
            }
        }
        private static T FindVisualParent<T>(UIElement element) where T : UIElement
        {
            UIElement parent = element;
            while (parent != null)
            {
                T correctlyTyped = parent as T;
                if (correctlyTyped != null)
                {
                    return correctlyTyped;
                }
               parent = VisualTreeHelper.GetParent(parent) as UIElement;
            }
            return null;
        }
        //End of single click selection
        
        
        
        private void button2_Click(object sender, RoutedEventArgs e)
        {
            iteratorDG();
        }

        public void iteratorDG()
        {
            var totalcount = LibraryView.Items.Count;
            for (int i=0; i < totalcount; i++)
            //for (int i = 0; i < 17; i++)
            {
               var cellData = GetCell(LibraryView, i, 1);
                if (cellData != null)
                {   
                    var txtCellData = cellData.Content as TextBlock;
                    var id = txtCellData.Text;
                    Console.WriteLine(i);
                    var pathOfExe = System.AppDomain.CurrentDomain.BaseDirectory;
                    var relativeToExe = pathOfExe + "test.mdb";
                    var con = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source = " + relativeToExe);
                    var cmd = new OleDbCommand();
                    cmd.Connection = con;
                    try
                    {
                        con.Open();
                    }
                    catch(Exception ex)
                    {
                        Console.WriteLine(ex);
                    }
                    //string strAccessSelect = "SELECT ClientId FROM Clients Where ClientId=@clientId";
                    string strAccessSelect = "SELECT Clients.['ClientId'] FROM Clients Where (((Clients.['ClientId'])=@p1))";
                    //string query3 = "DELETE Clients.['ClientId'] FROM Clients WHERE (((Clients.['ClientId'])='" + el.Value + "'))";
                    
                     OleDbCommand commandSelect = new OleDbCommand(strAccessSelect, con);
                     commandSelect.Parameters.Add("@p1", OleDbType.VarChar);
                     commandSelect.Parameters["@p1"].Value = id;
                     //commandSelect.CommandText = strAccessSelect;
                     //commandSelect.Connection = con;
                     


                     try
                     {
                         
                         OleDbDataReader resultSet = commandSelect.ExecuteReader();
                         if (resultSet.HasRows)
                         {
                             GetCell(LibraryView, i, 1).Background = Brushes.Yellow;
                         }
                     }
                     catch (Exception ex)
                     { Console.WriteLine(ex.ToString()); }
                     con.Close();
                }
                
            }
        }

        DataGridCell GetCell(DataGrid LibraryView, int rowIndex, int columnIndex)//returns a grid cell data on specifing row and column
        {
                var dr = LibraryView.ItemContainerGenerator.ContainerFromIndex(rowIndex) as DataGridRow;
                if (dr == null)
                {
                    return null;
                }
                var dc = LibraryView.Columns[columnIndex].GetCellContent(dr);
                return dc.Parent as DataGridCell;
        }

        private void Page_Loaded(object sender, RoutedEventArgs e)//place timer for checking internet conectivity on page load
        {
            DispatcherTimer dispatcherTimer = new DispatcherTimer();
            dispatcherTimer.Tick += new EventHandler(dispatcherTimer_Tick);
            dispatcherTimer.Interval = new TimeSpan(0, 0, 15); //15 second delay
            dispatcherTimer.Start();
        }

        private void dispatcherTimer_Tick(object sender, EventArgs e)//update internet status
        {
            bool checkInternet = CheckConnection("http://www.digiply.com:8020/MyAPIWebService.svc/getUser");
            if (checkInternet == true)
            {
                statusTxtBlock.Text = "Online";
            }
            else
            {
                statusTxtBlock.Text = "Offline";
            }
        }
        private bool CheckConnection(String URL)//function to check internet
        {
            try
            {
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(URL);
                request.Timeout = 15000; //15second
                request.Credentials = CredentialCache.DefaultNetworkCredentials;
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                var done=1;
                var single = done;
                if (response.StatusCode == HttpStatusCode.OK) return true;
                else return false;
            }
            catch(Exception ex)
            {
                return false;
            }
        }
        }
     }

